package org.chen.admin.web.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.chen.admin.web.service.LoginService;
import org.chen.common.constant.CacheConstants;
import org.chen.common.constant.Constants;
import org.chen.common.constant.UserConstants;
import org.chen.common.core.domain.AjaxResult;
import org.chen.common.core.domain.model.LoginUser;
import org.chen.common.dto.LoginBody;
import org.chen.common.exception.ServiceException;
import org.chen.common.exception.user.BlackListException;
import org.chen.common.exception.user.CaptchaExpireException;
import org.chen.common.exception.user.UserNotExistsException;
import org.chen.common.exception.user.UserPasswordNotMatchException;
import org.chen.common.manager.AsyncManager;
import org.chen.common.redis.RedisCache;
import org.chen.common.service.ISysConfigService;
import org.chen.common.service.ISysUserService;
import org.chen.common.utils.MessageUtils;
import org.chen.common.utils.StringUtils;
import org.chen.common.utils.ip.IpUtils;
import org.chen.common.utils.uuid.DateUtils;
import org.chen.framework.context.AuthenticationContextHolder;
import org.chen.framework.manager.AsyncFactory;
import org.chen.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysConfigService configService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService userService;


    @Override
    public AjaxResult login(LoginBody loginBody) {
        log.info("登录测试:{}", loginBody);
        AjaxResult result = AjaxResult.success("登录成功");
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();

        //校验验证码
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;

        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);

            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,
                        Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(
                AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))
        );
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());

        String token = tokenService.createToken(loginUser);
        result.success(token);
        return result;
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    private void loginPreCheck(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
//        IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     验证码的唯一标识
     */
    private void validateCaptcha(String username, String code, String uuid) {
//        从redis中取出验证码，进行校验
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
//    可能出现的情况：
//        1.验证码已经过期了
        if (captcha == null) {
            //当验证码未找到，那么就是已经过期了，要记录一次登录失败日志，日志原因就是“验证码已过期”，这些操作需要另外一个线程来完成
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
//            2.验证码未过期，但是不正确
        if (!captcha.equalsIgnoreCase(code)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaExpireException();
        }
//                3.验证码正确,
        redisCache.deleteObject(verifyKey);


    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        userService.updateLoginInfo(userId, IpUtils.getIpAddr(), DateUtils.getNowDate());
    }
}
